package com.panda.pandawash.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.VersionInfoBean;
import com.panda.pandawash.service.DownloadServices;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.panda.pandawash.R;
import com.panda.pandawash.util.CDNetWorkUtil;
import com.panda.pandawash.view.StatusBarCompat;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;


@ContentView(R.layout.activity_update)
public class UpdateActivity extends AppCompatActivity {
    private final String TAG = "UpdateActivity";
    private String download_url;
    private VersionInfoBean myVersionInfoBean;
    private String now_version = "";
    private int now_code = 0;
    private static final int MSG_UPDATE_NEW_VERSON = 0x100;
    private static final int MSG_IS_THE_LATEST_ED = 0x101;
    private static final int MSG_IS_NO_VERSON = 0x102;
    private SharedPreferences preferences;

    private ProgressDialog dialog = null;

    public static final String UPDATE_URL = "http://yslink.xyz/motor_th/index.php/Admin/AppsXMJX/LastAndroidVersion";

    @ViewInject(R.id.btn_update_return)
    private ImageButton btn_return;

    @ViewInject(R.id.toggleButton)
    private ToggleButton updateToggleButton;

    @ViewInject(R.id.view_update)
    private RelativeLayout update_layout;

    @ViewInject(R.id.view_about)
    private RelativeLayout about_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }
        x.view().inject(this);

        now_version = CDApplication.getIntance().getVersion();
        now_code = CDApplication.getIntance().getVersionCode();

        preferences = getSharedPreferences("update", Context.MODE_PRIVATE);
        boolean isAutoUpdate = preferences.getBoolean("is_auto_update", true);
        updateToggleButton.setChecked(isAutoUpdate);

        updateToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                preferences = getSharedPreferences("update", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("is_auto_update", isChecked);
                editor.commit();
            }
        });

    }

    @Event(R.id.btn_update_return)
    private void viewReturnOnclick(View v) {
        Log.e("hys12345","into return");
        finish();
    }

    @Event(R.id.view_update)
    private void viewUpdateOnclick(View v) {
        if (CDApplication.getIntance().isNetworkAvailable(this)) {
            showUpdatingDialog();
            BDAutoUpdateSDK.uiUpdateAction(this, new MyUICheckUpdateCallback());
        } else {
            Toast.makeText(this, "没有可用的网络", Toast.LENGTH_LONG).show();
        }

    }

    private void showUpdatingDialog() {
        if (dialog != null)
            dialog.dismiss();
        dialog = new ProgressDialog(this);
        dialog.setIndeterminate(true);
        dialog.setMessage("正在检测版本，请稍等...");
        dialog.show();
    }

    private class MyUICheckUpdateCallback implements UICheckUpdateCallback {
        @Override
        public void onCheckComplete() {

            Log.d(TAG, "MyUICheckUpdateCallback--onCheckComplete");
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
        }
    }
    @Event(R.id.view_about)
    private void viewAboutOnclick(View v){
        Intent myIntent = new Intent();
        myIntent.setClass(this, AboutActivity.class);
        startActivity(myIntent);
    }


    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_UPDATE_NEW_VERSON:
                    if (CDNetWorkUtil.isNetworkAvailable(UpdateActivity.this)) {
                        startDownloadService(0, download_url);
                    } else {
                        Toast.makeText(UpdateActivity.this, "没有可用的网络", Toast.LENGTH_LONG).show();
                    }

                    break;

                case MSG_IS_THE_LATEST_ED:
                    Intent myIntent = new Intent();
                    myIntent.setClass(UpdateActivity.this, UpdateAppActivity.class);
                    startActivity(myIntent);

                    break;
                case MSG_IS_NO_VERSON:
                    Toast.makeText(UpdateActivity.this, "当前软件版本异常，请到官网重新下载安装", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }

        }

    };
    private void getVersionInfo(String key, String value, String url, final int id) {
        RequestParams params = new RequestParams();
        params.addBodyParameter(key, value);
        new HttpUtils().send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(UpdateActivity.this, "服务器维护中...", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                String date = arg0.result.toString();

                Gson gson = new GsonBuilder().serializeNulls().create();
                myVersionInfoBean = gson.fromJson(date, VersionInfoBean.class);
                String downloadVersion = myVersionInfoBean.getVersion();

                Message msg = new Message();

                if (myVersionInfoBean.getResultCode().equals("200")) {

                    if (downloadVersion == null || downloadVersion == "") {
                        msg.what = MSG_IS_THE_LATEST_ED;
                        myHandler.sendMessage(msg);
                        return;
                    }

                    download_url = "http://yslink.xyz/motor_th" + myVersionInfoBean.getFileSubUrl();

                    if (now_version != "" && now_version != null
                            && !now_version.equals(UpdateActivity.this.getString(R.string.can_not_find_version_name))) {

                        if (CDApplication.getIntance().isUpdate(now_version, downloadVersion)) {
                            msg.what = MSG_UPDATE_NEW_VERSON;
                        } else {
                            msg.what = MSG_IS_THE_LATEST_ED;
                        }

                    } else {
                        msg.what = MSG_IS_NO_VERSON;
                    }
                    myHandler.sendMessage(msg);
                }


            }

        });
    }

    private void startDownloadService(int notifyId, String url) {

        Intent i = new Intent(this, DownloadServices.class);
        i.putExtra("url", url);
        i.putExtra("notifyId", notifyId);
        this.startService(i);
    }
}
